package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import svgedit.gui.Frame;

/**
 * Shows confirm changes dialog, then exits the application.
 */
public class QuitAction extends AbstractAction implements WindowListener
{
	private static final long serialVersionUID = 5532356112701737494L;

	/** Create this action for the given frame */
	public QuitAction()
	{
		super("Quit");
	}

	/**
	 * Handler for quit menuItem press checks if changes has been made and saves
	 * the file (if opted to)
	 */
	public void actionPerformed(ActionEvent ae)
	{
		// only show dialog if the file is modified.
		if (!Frame.getFrame().getChangesMade())
			System.exit(0);

		int res = confirmBox();
		if (res == JOptionPane.YES_OPTION)
		{
			save();
		}
		else if (res == JOptionPane.NO_OPTION)
		{
			System.exit(0);
		}
	}

	/**
	 * Handler for the close operation. checks if changes has been made and
	 * saves the file (if opted to)
	 */
	@Override
	public void windowClosing(WindowEvent arg0)
	{
		// only show dialog if the file is modified.
		if (!Frame.getFrame().getChangesMade())
			System.exit(0);

		int res = confirmBox();
		if (res == JOptionPane.YES_OPTION && Frame.getFrame().getChangesMade())
		{
			save();
		}
		else if (res == JOptionPane.NO_OPTION)
		{
			System.exit(0);
		}
	}

	/**
	 * Just a wrapper method to call Frame.saveFile();
	 */
	private void save()
	{
		Frame f = Frame.getFrame();
		f.saveFile(Frame.DIALOG_MODE_CHECK);

	}

	/**
	 * Wrapper method to call Frame.displaySaveDialog();
	 * 
	 * @return the result of the user input from the JOptionPane
	 */
	private int confirmBox()
	{
		Frame f = Frame.getFrame();
		return f.displaySaveDialog();
	}

	/* All these arent needed but have to be here... */
	@Override
	public void windowActivated(WindowEvent arg0)
	{
	}

	@Override
	public void windowClosed(WindowEvent arg0)
	{
	}

	@Override
	public void windowDeactivated(WindowEvent arg0)
	{
	}

	@Override
	public void windowDeiconified(WindowEvent arg0)
	{
	}

	@Override
	public void windowIconified(WindowEvent arg0)
	{
	}

	@Override
	public void windowOpened(WindowEvent arg0)
	{
	}

}
